package newcrunch.grader;

import java.util.Collections;
import java.util.List;
import javax.swing.AbstractListModel;

/**
 *
 * @author ccadm
 */
public class GradingListModel extends AbstractListModel
{
    private boolean[] disabled;
    private boolean[] showName;
    private String[] data;
    private int showNameCount;
    private List<SubmissionInfo> submissionsCache;
    
    public GradingListModel()
    {
        disabled = new boolean[0];
        showName = new boolean[0];
        data = new String[0];
    }
    
    public GradingListModel(List<String> items, List<SubmissionInfo> submissionsCache)
    {
        data = new String[items.size()];
        disabled = new boolean[items.size()];
        showName = new boolean[items.size()];
        
        for (int i = 0; i < items.size(); i++)
            data[i] = items.get(i);
        
        this.submissionsCache = submissionsCache;
    }
    
    @Override
    public int getSize() {
        return data.length;
    }

    @Override
    public Object getElementAt(int index) {
        return data[index];
    }

    public void setElementAt(int index, String val)
    {
        data[index] = val;
    }
    
    public void setDisabled(int index)
    {
        disabled[index] = true;
    }
    
    public boolean isDisabled(int index)
    {
        return disabled[index];
    }
    
    public void showName(int index)
    {
        String username = this.getElementAt(index).toString();
        String name = getName(username);
        this.setElementAt(index, username + " (" + name + ")");
        
        showNameCount++;
        showName[index] = true;
    }
    
    public void showAllNames()
    {
        for (int i = 0; i < getSize(); i++)
            if (!isShowingName(i))
                showName(i);
    }
    
    public void hideName(int index)
    {
        if (isShowingName(index))
        {
            String orig = this.getElementAt(index).toString();
            String username = orig.substring(0, orig.indexOf(" "));
            this.setElementAt(index, username);
        
            showNameCount--;
            showName[index] = false;
        }
    }
    
    public void hideAllNames()
    {
        for (int i = 0; i < getSize(); i++)
            hideName(i);
    }
    
    public int getShowNameCount()
    {
        return showNameCount;
    }
    
    public boolean isShowingName(int index)
    {
        return showName[index];
    }
    
    public String getName(String username)
    {
        int index = Collections.binarySearch(submissionsCache, new SubmissionInfo(username), 
                new UsernameComparator());
        
        return index >= 0 ? submissionsCache.get(index).firstname : null;
    }
}
